package org.framework.core.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.framework.core.error.ExceptionHandle;
import org.framework.core.error.support.Errors;
import org.framework.core.override.context.ContextRegister;
import org.framework.core.validate.Validation;
import org.framework.core.validate.ValidationAdapter;
import org.framework.core.validate.exception.ValidationException;
import org.framework.core.web.handler.ServiceHandler;
import org.framework.define.bean.result.Errcode;
import org.framework.define.bean.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ServiceController implements ExceptionHandle {
	
	private static Logger log = LogManager.getLogger(ServiceController.class);
	
	@RequestMapping(value="{module}/{method}", method={RequestMethod.GET, RequestMethod.POST})
	public ModelAndView executeRequest(HttpServletRequest request, @RequestParam Map<String,String> params, @PathVariable String module, @PathVariable String method) throws Exception {
		
		String mapping = module+"$"+method;
		//param validation
		Validation<Map<String,String>> vld = ValidationAdapter.getInstance();
		Errcode errcode = vld.validate(request, params, mapping);
		if(!errcode.equals(Errors.OK))
			throw new ValidationException(errcode);

		//handle execute
		ModelAndView view = new ModelAndView();
		Errcode result = ContextRegister.CONTEXT.getBean(mapping, ServiceHandler.class).execute(request, params);
		view.addObject("result", result);

		return view;
	}

	
	public ModelAndView handleCustomException(HttpServletRequest request, HttpServletResponse response, Object handler, ValidationException ex) {
		
		ModelAndView view = new ModelAndView();
		log.debug(ex.getMessage());
		view.addObject(ex.toResult());
		return view;
	}
	
	public ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		
		ModelAndView view = new ModelAndView();
		view.addObject(new Result(Errors.EXCEPTION_UNKNOW, ex.getMessage()));
		log.error("EXCEPTION_UNKNOW", ex);
		return view;
	}
	
}